/*
 * File:   ServerSocket.cpp
 * Author: samcrow
 *
 * Created on March 14, 2012, 6:01 PM
 */

#include "ServerSocket.hpp"

using namespace std;

ServerSocket::ServerSocket(int port) {


	int tempSocket = socket(AF_INET, SOCK_STREAM, 0);

	if(tempSocket < 0){
		cout << "Error opening socket. socket() returned " << tempSocket << ", errno=" << errno << "." << endl;
	}

	struct sockaddr_in serverAddress;
	//C: Initialize everything in the serverAddress to 0
	bzero((char *) &serverAddress, sizeof(serverAddress));
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(port);//htons() converts from the system byte order to the standard networking byte order
	serverAddress.sin_addr.s_addr = INADDR_ANY;//Maybe this makes it listen on all the addresses?

	//Bind to the port
	int bindValue = bind(tempSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress));
	if(bindValue < 0){
		cout << "Error binding socket to port " << port << ". returned " << bindValue << ", errno=" << errno << "." << endl;
	}

	listen(tempSocket, 5);//Start listening

	struct sockaddr_in cli_addr;//I don't know what this does
	socklen_t clilen = sizeof(cli_addr);//I don't know what this does
	bzero((char *) &cli_addr, clilen);


	cout << "About to block waiting for a connection..." << endl;
	int newSocket = accept(tempSocket, (struct sockaddr *) &cli_addr, &clilen);
	if(newSocket < 0){
		cout << "Socket accept error. Returned " << newSocket << ", errno=" << errno << "." << endl;
	}
	cout << "Got a connection. New socket ID: " << newSocket << endl;

	m_socket = newSocket;//Set this instance's socket ID
}

int ServerSocket::send(std::string text){
	return write(m_socket, text.c_str(), text.length());
}

ServerSocket::~ServerSocket() {
	close(m_socket);
}

